<?php
 	function smarty_function_rss($params, &$smarty){
		global $setupdata;
		$cacheTMP = $setupdata['smarty_admin_template_dir']."guest/rss.html";
		
		if(empty($params['source'])) return;
		if(!empty($params['items'])) $itemsToGet = (int)$params['items'];
		else $itemsToGet = 0;
		
		//cache feed?
		if(!empty($params['cache'])){
			if($params['cache'] == 'false') $cache = false;
			else $cache = true;
		} else {
			$cache = true;
		}
		
		//cache lifetime
		if(!empty($params['cachelt'])) $lifeTime = (int)$params['cachelt'];
		else $lifeTime = 86400;
		
		$oldCacheStatus = $smarty->caching;
		$oldCacheLifetime = $smarty->cache_lifetime;
		$smarty->caching = $cache;
		$smarty->cache_lifetime = $lifeTime;
		$cacheID = "rss|".md5($params['source']);
		
		//was the feed cached?
		if(!$smarty->is_cached($cacheTMP, $cacheID)){ //no
			if(@ini_get("allow_url_fopen") == 0) @ini_set("allow_url_fopen", 1);
			if($file = fopen($params['source'],"r")){
				$content = '';
				while (!feof($file)) $content .= fread($file, 8192);
				fclose($file);
			}else{
				return;
			}
			$smarty->assign("someData", $content);
			
		}
		
		$content = $smarty->fetch($cacheTMP, $cacheID);
		
		$smarty->caching = $oldCacheStatus;
		$smarty->cache_lifetime = $oldCacheLifetime;
		
		$items = explode("<item", $content);
		unset($items[0]); //drop first reference
		
		$data = array();
		$tempArray = array();
		$counter = 0;
		
		foreach($items as $item){
			$tempArray['title'] = untag($item,"title");
			$tempArray['description'] = untag($item,"description");
			$tempArray['link'] = untag($item,"link");
			$data[] = $tempArray;
			if ($itemsToGet > 0){
				$counter++;
				if($counter >= $itemsToGet){
					break;
				}
			}
		}

		if (isset($params["assign"])) $smarty->assign($params["assign"], $data);
		else return $data;
	}
	
	function untag ($string, $tag){
		$z = strpos ($string, '<'.$tag.'>');
		if ($z!==false) {
			$z=$z+ strlen ($tag) + 2;
			$z2 = strpos ($string, '</'.$tag.'>');
			$s = substr ($string, $z, $z2 - $z);
			return $s;
		}
	}
?>